package com.alibaba.sentinelannotation;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author YL
 * @date 16:30 2021/10/3
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/hello")
    @SentinelResource(value = "hello", blockHandler = "block")
    public String hello() {
        return "hello";
    }

    public String block(BlockException ex) {
        log.warn("服务被限流或降级了{}", ex.getMessage());
        return "服务被限流或降级了";
    }

    @GetMapping("/degrade")
    @SentinelResource(value = "degrade", blockHandler = "degradeBlock", fallback = "degradeFallback")
    public String apiHello(@RequestParam(required = false) String name) {
        if (StringUtil.isEmpty(name)) {
            throw new IllegalArgumentException("参数为空");
        }
        return "mtcarpenter:" + name;
    }

    public String degradeBlock(String name, BlockException ex) {
        log.warn("服务被限流或降级了 block{}  {}", name, ex.getMessage());
        return "服务被限流或降级了 block";
    }

    public String degradeFallback(String name) {
        log.warn("服务被限流或降级了 异常fallback");
        return "服务被限流或降级了 异常fallback";
    }

    @GetMapping("/hot")
    @SentinelResource(value = "hot",blockHandler = "block",blockHandlerClass = BlockHandlerClassException.class,fallback = "fallback",fallbackClass = FallbackClassException.class)
    public String hot(@RequestParam("productId") String productId, @RequestParam("key") String key) {
        return productId + "----" + key;
    }
}
